import { computed, inject, ref } from 'vue'
import {  opType } from '../imgTypes'

interface IGlobalOp {
  [key: string]: opType
}

const globalOpRef = ref<IGlobalOp>({})

export const useActiveOp = () => {
  const windowId = inject('windowId') as any;
  const activeOp = {
    type: '',
    subType: ''
  }
  if (!globalOpRef.value[windowId]) {
    globalOpRef.value[windowId] = activeOp
  }

  function setActiveOp(activeOp: opType) {
    const currentActiveOp = globalOpRef.value[windowId]
    checkOp(currentActiveOp, activeOp)
  }


  function checkOp(currentOp: opType, newOp: opType) {
    if (currentOp.type === newOp.type && currentOp.subType === newOp.subType) {
      clearActiveOp()
      return
    }
    globalOpRef.value[windowId] = newOp
  }


  function clearActiveOp() {
    globalOpRef.value[windowId] = {
      type: '',
      subType: ''
    }
  }


  return {
    activeOp: computed(() =>  globalOpRef.value[windowId]),
    setActiveOp
  }
}
